<template>
  <div>
    <div class="toolbar">
      <el-input v-model="keyword" placeholder="按学号或姓名搜索" style="width: 240px;" clearable />
      <el-input-number v-model="classId" :min="0" :max="999999" placeholder="班级ID" />
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="success" @click="openCreate">新增学生</el-button>
    </div>

    <el-table :data="items" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="studentNo" label="学号" width="140" />
      <el-table-column prop="name" label="姓名" width="140" />
      <el-table-column prop="gender" label="性别" width="100" />
      <el-table-column prop="classId" label="班级ID" width="110" />
      <el-table-column prop="status" label="状态" width="140" />
      <el-table-column prop="phone" label="电话" width="160" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-popconfirm title="确认删除该学生？" @confirm="doDelete(row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page"
      :page-size="limit"
      :total="total"
      background
      layout="prev, pager, next"
      @current-change="load"
      class="pagination"
    />

    <el-dialog v-model="dialogVisible" :title="editing ? '编辑学生' : '新增学生'" width="600">
      <el-form :model="form" label-width="100px">
        <el-form-item label="学号"><el-input v-model="form.studentNo" /></el-form-item>
        <el-form-item label="姓名"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="性别">
          <el-select v-model="form.gender" placeholder="选择">
            <el-option label="男(M)" value="M" />
            <el-option label="女(F)" value="F" />
            <el-option label="未知(U)" value="U" />
          </el-select>
        </el-form-item>
        <el-form-item label="院系">
          <el-select v-model="form.deptId" placeholder="选择院系" filterable style="width: 240px">
            <el-option v-for="d in deptOptions" :key="d.id" :label="d.name" :value="d.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="form.majorId" placeholder="选择专业" filterable style="width: 240px">
            <el-option v-for="m in majorOptions" :key="m.id" :label="m.name" :value="m.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="form.classId" placeholder="选择班级" filterable style="width: 240px">
            <el-option v-for="c in classOptions" :key="c.id" :label="c.name" :value="c.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="选择">
            <el-option label="在读" value="ENROLLED" />
            <el-option label="休学" value="SUSPENDED" />
            <el-option label="退学" value="WITHDRAWN" />
            <el-option label="毕业" value="GRADUATED" />
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期">
          <el-date-picker v-model="form.enrollmentDate" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="电话"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="邮箱"><el-input v-model="form.email" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { listStudents, createStudent, updateStudent, deleteStudent, type Student } from '@/api/grades/students'
import { listDepartments, type Department } from '@/api/grades/departments'
import { listMajors, type Major } from '@/api/grades/majors'
import { listClasses, type Clazz } from '@/api/grades/classes'

const loading = ref(false)
const items = ref<Student[]>([])
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const keyword = ref('')
const classId = ref<number | undefined>(undefined)

const dialogVisible = ref(false)
const editing = ref(false)
const form = ref<Student>({})
const deptOptions = ref<Department[]>([])
const majorOptions = ref<Major[]>([])
const classOptions = ref<Clazz[]>([])

async function load() {
  loading.value = true
  try {
    const res = await listStudents({ keyword: keyword.value || undefined, classId: classId.value, offset: (page.value - 1) * limit.value, limit: limit.value })
    items.value = res.items
    total.value = res.total
  } finally {
    loading.value = false
  }
}

function openCreate() {
  editing.value = false
  form.value = { gender: 'U', status: 'ENROLLED' }
  dialogVisible.value = true
}

function openEdit(row: Student) {
  editing.value = true
  form.value = { ...row }
  dialogVisible.value = true
  loadMajorOptionsFor(form.value.deptId)
  loadClassOptionsFor(form.value.majorId)
}

async function submit() {
  try {
    if (editing.value && form.value.id) {
      await updateStudent(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createStudent(form.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '操作失败')
  }
}

async function doDelete(id?: number) {
  if (!id) return
  try {
    await deleteStudent(id)
    ElMessage.success('已删除')
    await load()
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}

onMounted(() => {
  load()
  loadDeptOptions()
})

async function loadDeptOptions() {
  try {
    const res = await listDepartments({ pageNum: 1, pageSize: 1000 })
    deptOptions.value = res.items
  } catch {}
}

async function loadMajorOptionsFor(deptId?: number) {
  try {
    if (!deptId) { majorOptions.value = []; form.value.majorId = undefined; return }
    const res = await listMajors({ deptId, pageNum: 1, pageSize: 1000 })
    majorOptions.value = res.items
  } catch {}
}

async function loadClassOptionsFor(majorId?: number) {
  try {
    if (!majorId) { classOptions.value = []; form.value.classId = undefined; return }
    const res = await listClasses({ majorId, pageNum: 1, pageSize: 1000 })
    classOptions.value = res.items
  } catch {}
}

watch(() => form.value.deptId, (val) => {
  loadMajorOptionsFor(val)
  classOptions.value = []
  form.value.classId = undefined
})

watch(() => form.value.majorId, (val) => {
  loadClassOptionsFor(val)
})
</script>

<style scoped>
.toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}
.pagination {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>